package com.lngsyz.file.config.cors;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.httpclient.HttpStatus;   //这里需要添加commons-httpclient-3.1.jar
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@WebFilter
public class CorsFilter implements Filter {     //filter 接口的自定义实现
	
	private static final Logger LOGGER = LoggerFactory.getLogger(CorsFilter.class);
	
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        response.setHeader("Access-Control-Allow-Origin", "*");           
        // String token = request.getHeader("token");
        // System.out.println("filter origin:"+token);//通过打印，可以看到一次非简单请求，会被过滤两次，即请求两次，第一次请求确认是否符合跨域要求（预检），这一次是不带headers的自定义信息，第二次请求会携带自定义信息。
        if ("OPTIONS".equals(request.getMethod())){//这里通过判断请求的方法，判断此次是否是预检请求，如果是，立即返回一个204状态吗，标示，允许跨域；预检后，正式请求，这个方法参数就是我们设置的post了
          response.setStatus(HttpStatus.SC_NO_CONTENT); //HttpStatus.SC_NO_CONTENT = 204
          response.setHeader("Access-Control-Allow-Methods", "POST, GET, DELETE, OPTIONS, DELETE");//当判定为预检请求后，设定允许请求的方法
          response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Authorization, Devicetype"); //当判定为预检请求后，设定允许请求的头部类型
          response.addHeader("Access-Control-Max-Age", "3600");  // 预检有效保持时间         最大7200         
          return;
        }
        long start = System.currentTimeMillis();
        try {
        	filterChain.doFilter(servletRequest, servletResponse);
        	// LOGGER.info("Filter cost time : " + (System.currentTimeMillis() - start) + "ms");
        } catch(Exception e) {
        	String requestURI = request.getRequestURI();
        	// 针对ioException broken pipe异常
			if(e instanceof ClientAbortException){
				LOGGER.info("*****************用户中断请求造成的异常");
        	}
			LOGGER.info("Filter cost time : " + (System.currentTimeMillis() - start) + "ms");
			LOGGER.error("业务异常信息：[{}]", e.getMessage(), e);
			LOGGER.info("业务异常信息（URI）：[{}]", requestURI);
            return;
        }
    }
    @Override
    public void destroy() {     
    }
}